<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RichTextEditor from '@/components/RichTextEditor.vue'
import {
  fetchCinemaPage,
  createCinema,
  updateCinema,
  deleteCinema,
  deleteCinemaBatch,
  getCinemaById,
} from '@/api/cinema'

const loading = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const query = reactive({ cname: '', status: '' })

const multipleSelection = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增影院')
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  id: null,
  cname: '',
  address: '',
  phone: '',
  status: 'OPEN',
  description: '',
  // 新增字段：影厅列表 JSON 字符串（如 ["1号厅","2号厅"]) 
  hallList: '',
})


// 文本形式的影厅输入，每行一个影厅名称，提交时转换为 JSON
const hallInputText = ref('')

const rules = {
  cname: [{ required: true, message: '请输入影院名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^\d{3,4}-?\d{7,8}$|^1[3-9]\d{9}$/u, message: '电话格式不正确', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

function loadData() {
  loading.value = true
  fetchCinemaPage({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    cname: query.cname || undefined,
    status: query.status || undefined,
  })
    .then((res) => {
      if (String(res.code) === '200') {
        list.value = res.data?.records || []
        total.value = res.data?.total || 0
      } else {
        ElMessage.error(res.msg || '查询失败')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function handleQuery() {
  pageNo.value = 1
  loadData()
}

function resetQuery() {
  query.cname = ''
  query.status = ''
  handleQuery()
}

function handleSelectionChange(rows) {
  multipleSelection.value = rows || []
}

function handleAdd() {
  dialogTitle.value = '新增影院'
  isEdit.value = false
  Object.assign(form, { id: null, cname: '', address: '', phone: '', status: 'OPEN', description: '', hallList: '' })
  // 重置影厅输入
  hallInputText.value = ''
  dialogVisible.value = true
}

/**
 * 编辑影院：支持加载详情以获取 hallList(JSON) 并转换为文本编辑
 * - 调用后端详情接口获取完整数据（包括 hallList）
 * - 将 hallList(JSON 数组) 转为多行文本，每行一个影厅名称
 */
async function handleEdit(row) {
  dialogTitle.value = '编辑影院'
  isEdit.value = true
  try {
    const res = await getCinemaById(row.id)
    if (String(res.code) === '200') {
      const data = res.data || row
      Object.assign(form, data)
      // 将 hallList(JSON 字符串) 转为多行文本
      try {
        const arr = Array.isArray(data.hallList)
          ? data.hallList
          : JSON.parse(data.hallList || '[]')
        hallInputText.value = (arr || []).filter(Boolean).join('\n')
      } catch (e) {
        hallInputText.value = ''
      }
    } else {
      Object.assign(form, row)
      hallInputText.value = ''
      ElMessage.warning(res.msg || '获取详情失败，已使用列表数据')
    }
  } catch (e) {
    Object.assign(form, row)
    hallInputText.value = ''
  }
  dialogVisible.value = true
}

/**
 * 提交影院表单：将影厅文本转换为 JSON 字符串写入 hallList 并提交
 * - 文本按行拆分，过滤空白，得到影厅数组
 * - 写入 form.hallList = JSON.stringify(影厅数组)
 * - 创建/更新影院后刷新列表
 */
function submitForm() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      // 将多行文本转换为 JSON 字符串
      const halls = hallInputText.value
        .split(/\r?\n/u)
        .map((s) => s.trim())
        .filter((s) => s.length > 0)
      form.hallList = JSON.stringify(halls)

      const api = isEdit.value ? updateCinema : createCinema
      const res = await api({ ...form })
      if (String(res.code) === '200') {
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        dialogVisible.value = false
        loadData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (e) {
      // 错误已在拦截器提示
    }
  })
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确认删除影院“${row.cname}”吗？`, '提示', { type: 'warning' })
    const res = await deleteCinema(row.id)
    if (String(res.code) === '200') {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) {
    // 取消或错误
  }
}

async function handleBatchDelete() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return ElMessage.warning('请先选择要删除的记录')
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条记录吗？`, '提示', { type: 'warning' })
    const res = await deleteCinemaBatch(ids)
    if (String(res.code) === '200') {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {}
}

function handleSizeChange(size) {
  pageSize.value = size
  pageNo.value = 1
  loadData()
}

function handleCurrentChange(page) {
  pageNo.value = page
  loadData()
}

function htmlToText(html) {
  if (!html) return ''
  const div = document.createElement('div')
  div.innerHTML = html
  return (div.textContent || div.innerText || '').trim()
}

onMounted(loadData)
</script>

<template>
  <div class="page">
    <div class="page-header">
      <div class="title">影院管理</div>
      <div class="actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增影院
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <el-card class="card" shadow="never">
      <el-form :inline="true" :model="query" class="query-form">
        <el-form-item label="影院名称">
          <el-input v-model="query.cname" placeholder="支持模糊查询" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable style="width: 180px">
            <el-option label="营业中" value="OPEN" />
            <el-option label="停业" value="CLOSED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card" shadow="never">
      <el-table
        :data="list"
        v-loading="loading"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="cname" label="影院名称" min-width="180" />
        <el-table-column prop="address" label="地址" min-width="220" />
        <el-table-column prop="phone" label="电话" width="140" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'OPEN' ? 'success' : 'info'">
              {{ row.status === 'OPEN' ? '营业中' : '停业' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="简介" min-width="220">
          <template #default="{ row }">
            <span class="desc">{{ htmlToText(row.description) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="pageNo"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="影院名称" prop="cname">
          <el-input v-model="form.cname" placeholder="请输入影院名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="座机或手机" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width: 180px">
            <el-option label="营业中" value="OPEN" />
            <el-option label="停业" value="CLOSED" />
          </el-select>
        </el-form-item>
        <el-form-item label="影厅列表">
          <el-input type="textarea" v-model="hallInputText" :rows="4" placeholder="每行代表一个影厅" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <RichTextEditor v-model="form.description" height="260px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page {
  padding: 16px;
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.title {
  font-size: 18px;
  font-weight: 600;
}
.card {
  margin-bottom: 12px;
}
.query-form :deep(.el-form-item) {
  margin-right: 12px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
.desc {
  display: inline-block;
  max-width: 380px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>